{% extends 'form.html' %}
{% load static i18n %}
{% block extra_css %}
{{ block.super }}
<style>
  .mailbox-attachments li {
    width: 230px !important;
  }

  .preview-container {
    display: grid;
    gap: 1rem;
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    margin-top: 10px;
    margin-bottom: 10px;
  }

  .has-img img {
    width: 230px !important;
    height: 230px !important;
    object-fit: contain;
  }

  .upload-container {
    padding: 10px;
    border: 2px dashed #ddd;
    border-radius: 10px;
    text-align: center;
    transition: border-color 0.3s;
    margin-bottom: 10px;
  }

  .upload-container.highlight {
    border-color: #1677ff;
    background-color: #f0f6ff;
  }

  .upload-prompt {
    font-size: 16px;
    color: #333;
    margin: 10px 0;
  }

  .upload-prompt span {
    color: #3c8dbc;
    cursor: pointer;
  }

  .supported-files {
    font-size: 12px;
    color: #666;
    margin: 15px 0;
    line-height: 1.5;
  }

  #file-input {
    display: none;
  }
</style>
{% endblock %}

{% block box_body %}
<form method="post" enctype="multipart/form-data" id="edit-form-htmx" novalidate>
  {% csrf_token %}
  <div class="upload-container" id="drop-zone">
    <div class="upload-prompt" id="uploadArea">
      拖拽图片至此，或者 <span onclick="document.getElementById('file-input').click()">选择图片</span>
    </div>
    <div class="supported-files">
      仅支持上传图片，每个文件不超过 15MB。
    </div>
    <input type="file" id="file-input" accept="image/*" multiple>
    <div class="file-preview preview-container" id="file-preview"></div>
    <!-- <button class="btn btn-sm btn-primary" id="next-button">下一步</button> -->
  </div>
  <ul class="mailbox-attachments clearfix" id="previewContainer"></ul>

  <div class="table">
    <table class="table table-bordered table-hover table-condensed text-nowrap">
      <thead>
        <tr>
          <th width="2%">#</th>
          <th width="12%">物品编号*</th>
          <th width="12%">唯一标识</th>
          <th width="22%">物品*</th>
          <th width="15%">租户*</th>
          <th width="15%">仓库*</th>
          <th width="10%">存放位置</th>
          <th width="5%">数量*</th>
          <th>标签</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>1.</td>
          {% for field in form %}
          <td>{{ field }}</td>
          {% endfor %}
        </tr>
      </tbody>
    </table>
  </div>
  <div class="box-footer">
    <div class="pull-right">
      <a href="{{ request.META.HTTP_REFERER }}" class="btn btn-default btn-sm margin-r-5" title="{% trans '取消并返回' %}">
        {% trans '返回' %}
      </a>
      <button type="submit" name="save" class="btn btn-primary btn-sm">{% trans '保存' %}</button>
    </div>
  </div>
</form>
{% endblock %}

{% block extra_js %}

{{ block.super }}
<script src="{% static 'js/choices.min.js' %}"></script>

<script>
  function initChoices() {
    const form = document.getElementById('edit-form-htmx');
    const selects = new Map(); // 存储所有select和其对应的错误状态

    document.querySelectorAll('select.form-control').forEach(select => {
      // 如果已经初始化过，跳过
      if (select._choice) return;

      // 保存原始的htmx触发器设置
      const originalTrigger = select.getAttribute('hx-trigger');
      // 暂时移除htmx触发器，避免重复触发
      if (originalTrigger) {
        select.removeAttribute('hx-trigger');
      }

      // 获取原生select的错误信息容器
      const errorContainer = select.parentElement.querySelector('.help-block');

      const choiceConfig = {
        removeItemButton: true,
        searchEnabled: true,
        shouldSort: false,
        sorter: () => [],
        allowHTML: true,
        position: 'auto',
        renderChoiceLimit: -1,
        // 所有提示信息改为中文
        searchPlaceholderValue: '搜索...',
        noResultsText: '没有找到匹配项',
        itemSelectText: '点击选择',
        loadingText: '加载中...',
        noChoicesText: '没有可选择的选项',
        // 添加按钮文本
        addItemText: (value) => {
          return `按回车键添加 <b>"${value}"</b>`;
        },
        maxItemText: (maxItemCount) => {
          return `最多只能选择${maxItemCount}项`;
        },
        // 自定义按钮和占位符文本
        customAddItemText: '只能添加符合此规则的选项',
        removeItemButton: true,
        duplicateItemsAllowed: false,
        // 分组相关文本
        classNames: {
          groupTitle: '选项组标题'
        },
      };

      // 针对 color 字段的特殊处理
      if (select.name === 'color') {
        choiceConfig.callbackOnCreateTemplates = function (template) {
          return {
            choice: (classNames, data) => {
              if (!data.value) return template(`
								<div style="margin-bottom: 3px; padding: 3px 0;" data-select-text="${this.config.itemSelectText}" data-choice data-choice-selectable data-id="${data.id}" data-value="${data.value}" role="option">
										<span style="margin: 0 10px; height:16px; display: inline-block;">${data.label}</span>
								</div>
							`);

              return template(`
								<div style="margin-bottom: 3px;" data-select-text="${this.config.itemSelectText}" data-choice data-choice-selectable data-id="${data.id}" data-value="${data.value}" role="option">
										<span class="label bg-${data.value}" style="margin: 0 5px; width:90px; height:12px; display: inline-block;"></span>${data.label}
								</div>
							`);
            },
            item: (classNames, data) => {
              if (!data.value) return template(`
								<div data-item data-id="${data.id}" data-value="${data.value}">
										<span style="margin-right: 5px; font-size: 85%;">${data.label}</span>
										<button type="button" class="choices__button" aria-label="Remove item: exclusive" data-button="">Remove item</button>
								</div>
							`);

              return template(`
								<div data-item data-id="${data.id}" data-value="${data.value}">
										<span class="label bg-${data.value}" style="margin-right: 5px; width:100px; font-size: 85%;">${data.label}</span>
										<button type="button" class="choices__button" aria-label="Remove item: exclusive" data-button="">Remove item</button>
								</div>
							`);
            }
          };
        };
      }
      // 创建 Choices 实例
      const choice = new Choices(select, choiceConfig);

      // 标记已初始化
      select._choice = choice;

      // 如果有htmx触发器，使用Choices的事件系统
      if (originalTrigger) {
        select.setAttribute('hx-trigger', originalTrigger);
      }

      // 创建错误提示元素
      let errorElement = document.createElement('span');
      errorElement.className = 'help-block';
      errorElement.style.display = 'none';
      choice.containerInner.element.parentElement.appendChild(errorElement);

      // 将select添加到Map中
      selects.set(select, {
        choice,
        errorElement,
        hasError: false
      });

      // 监听 Choices 的事件
      choice.passedElement.element.addEventListener('choice', function (event) {
        const value = choice.getValue(true);
        if (value) {
          errorElement.style.display = 'none';
          choice.containerInner.element.parentElement.classList.remove('has-error');
          selects.get(select).hasError = false;
        } else if (this.required) {
          errorElement.textContent = '此字段是必填项。';
          errorElement.style.display = 'block';
          choice.containerInner.element.parentElement.classList.add('has-error');
          selects.get(select).hasError = true;
        }
      });

      choice.passedElement.element.addEventListener('removeItem', function (event) {
        if (this.required && !choice.getValue(true)) {
          errorElement.textContent = '此字段是必填项。';
          errorElement.style.display = 'block';
          choice.containerInner.element.parentElement.classList.add('has-error');
          selects.get(select).hasError = true;
        }
      });

      // 如果已经有错误信息，立即显示
      if (errorContainer && errorContainer.textContent) {
        errorElement.textContent = errorContainer.textContent;
        errorElement.style.display = 'block';
        choice.containerInner.element.parentElement.classList.add('has-error');
        selects.get(select).hasError = true;
      }
    });

    // 监听表单提交
    form.addEventListener('submit', function (e) {
      e.preventDefault(); // 阻止默认提交

      let hasErrors = false;

      // 检查所有必填的select
      for (const [select, data] of selects) {
        const value = data.choice.getValue(true);
        if (select.required && !value) {
          data.errorElement.textContent = '此字段是必填项。';
          data.errorElement.style.display = 'block';
          data.choice.containerInner.element.parentElement.classList.add('has-error');
          data.hasError = true;
          hasErrors = true;
          // 聚焦到第一个错误的选择框
          if (!document.querySelector('.choices__input--cloned:focus')) {
            data.choice.showDropdown();
          }
        }
      }

      // 如果没有错误，提交表单
      if (!hasErrors) {
        form.submit();
      }
    });
  }

  // 等待 DOM 完全加载后初始化
  document.addEventListener('DOMContentLoaded', function () {
    initChoices();
  });

  // htmx加载完成后重新初始化
  document.body.addEventListener('htmx:afterSettle', function (evt) {
    initChoices();
  });
</script>
<script>
  const fileManager = {
    files: [],
    currentUploads: [] // 记录正在上传的文件索引
  };
  const uploadArea = document.getElementById('uploadArea');
  const dropZone = document.getElementById('drop-zone');
  const uploadInput = document.getElementById('file-input');
  const previewContainer = document.getElementById('previewContainer');

  // 获取CSRF Token
  function getCsrfToken() {
    return document.querySelector('[name=csrfmiddlewaretoken]').value;
  }

  // 设置拖拽区域样式
  dropZone.addEventListener('dragover', (e) => {
    e.preventDefault();
    e.stopPropagation();
    dropZone.style.borderColor = '#3498db';
  });

  dropZone.addEventListener('drop', (e) => {
    e.preventDefault();
    e.stopPropagation();
    dropZone.style.borderColor = '#ccc';
    const files = e.dataTransfer.files;
    for (const file of files) {
      if (file.type.startsWith('image/')) {
        previewImage(file);
      } else {
        alert('只能上传图片文件！');
      }
    }
  });

  function previewImage(file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      const fileInfo = {
        name: file.name,
        size: file.size,
        type: file.type,
        previewUrl: e.target.result,
        md5sum: '',
        describe: '', // 图片物品的描述
        category: '',
        serial_no: [], // 需要根据SN号计算物品数量
        model: '',
        part_no: '',
        wwn: '',
        keywords: [],
        extra_flags: [], // 后台OCR识别的疑似标识字符串列表
        interface: [],
        tags: [],
        manufacturer: [],
      };

      const liDom = document.createElement('li');
      const spanDom = document.createElement('span');
      spanDom.className = "mailbox-attachment-icon has-img";
      const img = document.createElement('img');
      img.src = e.target.result;
      img.alt = file.name;
      img.className = "img-responsive";
      spanDom.appendChild(img);
      liDom.appendChild(spanDom);
      previewContainer.appendChild(liDom);
      uploadImages(file, img, fileInfo);
      fileManager.files.push(fileInfo);
    };
    reader.readAsDataURL(file);
  }

  function uploadImages(file, img, fileInfo) {

    // 发送Ajax请求进行文件上传
    uploadFile(file, (response) => {
      if (response.files) {
        const data = response.files[0];
        console.log(data);
        img.src = data.url;
        img.alt = `文件名: ${data.name}, 大小: ${data.size} B`;
        fileInfo.md5sum = data.md5sum;

        // 检查文件是否存在于服务器
        if (data.exists === false) {
          console.warn(`警告: 文件 ${data.name} 在服务器上可能已被重新创建`);
          // 可以在UI中显示一个小的警告图标
          const warningSpan = document.createElement('span');
          warningSpan.className = "file-warning";
          warningSpan.innerHTML = '<i class="fa fa-warning text-warning" title="文件已被重新创建"></i>';
          img.parentNode.appendChild(warningSpan);
        }

        if (data.metadata && data.metadata.ocr_texts) {
          const ocr_raw_text = data.metadata.ocr_texts.join("\n");
          fileInfo.ocr_raw_text = ocr_raw_text;
          extractItemInfo(ocr_raw_text, (resp) => {
            if (resp.result) {
              const itemInfo = resp.result;
              console.log(itemInfo);
              const identifier = document.getElementById('id_identifier');
              identifier.value = itemInfo.serial_no;
              // 设置图片物品描述
              const liDom = img.closest('li');
              const itemInfoDom = `
                <div class="mailbox-attachment-info">
                    <span class="attachement-name">${file.name}</span>
                    <span class="mailbox-attachment-size">
                        名称: ${itemInfo.describe}</br>
                        品牌/制造商: ${itemInfo.manufacturer[0]?.name}</br>
                        SN号: ${itemInfo.serial_no}</br>
                        型号: ${itemInfo.model}<br>
                        部件编号: ${itemInfo.part_no}<br>
                        接口/协议: ${itemInfo.interface}<br>
                        标签: ${itemInfo.tags.join(", ")}
                    </span>
                </div>
                `;
              liDom.innerHTML += itemInfoDom;
            }
          })
        }
      } else {
        alert('文件上传失败！');
      }
    });
  }

  function extractItemInfo(rawText, callback) {
    const formData = new FormData();
    formData.append('raw_text', rawText);
    fetch('', {
      method: 'POST',
      headers: {
        'X-CSRFToken': getCsrfToken(),
      },
      body: formData
    })
      .then(response => response.json())
      .then(data => callback(data))
      .catch(error => console.error('Error:', error))
  }

  // 发送Ajax请求进行文件上传
  function uploadFile(file, callback) {
    const formData = new FormData();
    formData.append('files', file);
    formData.append('require_ocr', true);

    fetch('{% url "upload" %}', {
      method: 'POST',
      headers: {
        'X-CSRFToken': getCsrfToken(),
      },
      body: formData
    })
      .then(response => response.json())
      .then(data => callback(data))
      .catch(error => console.error('Error:', error));
  }

  // 监听文件输入
  uploadInput.addEventListener('click', () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.multiple = true;

    uploadInput.onchange = (e) => {
      for (const file of e.target.files) {
        if (file.type.startsWith('image/')) {
          previewImage(file);
        } else {
          alert('只能上传图片文件！');
        }
      }
    };

  });
</script>
{% endblock %}